package org.csu.onlineedubackend.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class JsonUtil {
    
    private static final ObjectMapper objectMapper = new ObjectMapper();
    
    /**
     * 將字符串列表轉換為 JSON 字符串
     * @param urls URL 列表
     * @return JSON 字符串
     */
    public static String urlsToJson(List<String> urls) {
        if (urls == null || urls.isEmpty()) {
            return "[]";
        }
        try {
            return objectMapper.writeValueAsString(urls);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("轉換 URL 列表為 JSON 失敗", e);
        }
    }
    
    /**
     * 將 JSON 字符串轉換為字符串列表
     * @param jsonUrl JSON 字符串
     * @return URL 列表
     */
    public static List<String> jsonToUrls(String jsonUrl) {
        if (jsonUrl == null || jsonUrl.trim().isEmpty()) {
            return List.of();
        }
        try {
            return objectMapper.readValue(jsonUrl, new TypeReference<List<String>>() {});
        } catch (JsonProcessingException e) {
            throw new RuntimeException("解析 JSON 為 URL 列表失敗", e);
        }
    }
    
    /**
     * 將對象轉換為 JSON 字符串
     * @param obj 對象
     * @return JSON 字符串
     */
    public static String objectToJson(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("對象轉 JSON 失敗", e);
        }
    }
    
    /**
     * 將 JSON 字符串轉換為對象
     * @param json JSON 字符串
     * @param clazz 目標類型
     * @return 對象
     */
    public static <T> T jsonToObject(String json, Class<T> clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON 轉對象失敗", e);
        }
    }
} 